package com.cms.util;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Hashtable;
import java.util.UUID;

import javax.imageio.ImageIO;

import com.cms.CommonAttribute;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.Result;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.jfinal.kit.PathKit;

/**
 * 二维码工具类
 *
 */
public class QrcodeUtils {

    public static String build(String content,int width,int height){
        Hashtable hints=new Hashtable();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
        hints.put(EncodeHintType.MARGIN, 2);
        try {
            BitMatrix bitMatrix=new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height,hints);
            String newFileName = UUID.randomUUID().toString()+".png";
            String url = "/"+CommonAttribute.UPLOAD_PATH+"/"+newFileName;
            Path file=new File(PathKit.getWebRootPath()+url).toPath();//生成二维码图片
            MatrixToImageWriter.writeToPath(bitMatrix, "png", file);
            return url;
        } catch (Exception e) {
        // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        }
    }
    
    
    public static String decode(File file){
        MultiFormatReader formatReader=new MultiFormatReader();
        BufferedImage image=null;
        try {
        image = ImageIO.read(file);
        } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        }
        BinaryBitmap binaryBitmap =new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(image)));
        Hashtable hints=new Hashtable();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        try{
            Result result=formatReader.decode(binaryBitmap,hints);
            System.err.println("解析结果："+result.toString());
            System.out.println(result.getBarcodeFormat());
            System.out.println(result.getText());
            return result.getText();
        }catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
            return null;
        }
    }
}
